package com.acceptable.qucun.generic.interceptor;

import com.acceptable.qucun.generic.util.CodeUtil;
import com.acceptable.qucun.generic.util.StringFormatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

@Component
public class RedisInterceptor implements HandlerInterceptor {
    @Autowired private StringRedisTemplate redisTemplate;

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        String key = (String) request.getAttribute("redis_key");
        String minutes =  String.valueOf(request.getAttribute("minutes"));
        if(StringFormatUtil.isEmpty(key))
            return;

        // 取请求处理方法中的request的数据 继续构造存入redis的key/value
        String value = CodeUtil.object2String(request.getAttribute("redis_map"));
        if(value == null)
            return;

        // 存入redis 有时间限制 过期删除
        redisTemplate.opsForValue().set(key, value, Duration.ofMinutes(Long.parseLong(minutes)));
    }
}
